<?php
/*=============================================================================
|| ##################################################################
||	phpFoX Konsort
|| ##################################################################
||
||	Copyright		: (C) 2005-2007 PHPFOX Limited a Reality Fox Creation
||	Contact			: info@phpfox.com
||
||	- phpFoX and all of its source code and files are protected by Copyright Laws.
||
||	- The license for phpFoX permits you to install this software on a single domain (.com, .org, .net, etc.).
||
||	- You may also not remove this copyright screen which shows the copyright information and credits for phpFoX (RealityFOX Creations).
||
||	- phpFoX Konsort is NOT a FREE software - http://www.phpfox.com/license/
||
|| ##################################################################
=============================================================================*/


class PhpFox_Mod_Video_ComponentUploadStream extends BaseComponent
{
    function process()
    {
    	App::checkUserAccess('video', 'full');

    	if ( !App::getParam('vid_allow_stream') )
    	{
    		App::gotoUrl('public.account');
    	}

    	App::loadClass('Validator');
        App::loadClass('file/Image');
        $oImage = &new file_Image();

        $aFields = array
        (
        	'val[vid_title]'   => array('title' => App::format('Mod_Video.add_form_title'), 'def' => 'required'),
        	'val[vid_url]'   => array('title' => App::format('Mod_Video.add_form_url'), 'def' => 'required'),
        );
        $oValidator = &new Validator($aFields, array());

		$oReq = &App::getRequest();

		$oSrvVideo = &$this->_oModule->getService('Video');

        list($iMemMaxUpload, $iUsedSpace, $iAllowedSpace, $iMaxUploadSize) = App::checkUserSize();

		if ($oReq->get('post_item'))
		{
			$oFile->aLimits['FILE_MAX_SIZE'] = (App::getMemConfig("vid_file_size") == 'iamnatio' ? 0 : App::getMemConfig("vid_file_size"));

		    if (!$oValidator->isValid($oReq->getAll()))
            {
                $this->addErrors($oValidator->getErrors());
            }

			$aPost = $oReq->getArray('val');

			if ( $aPost['stream_id'] == '0' && !$oSrvVideo->isAllowedExt($aPost['vid_url']) )
			{
				$this->addErrors(App::format('Mod_Video.upload_file_invalid', App::getParam('vid_allowed_ext')));
			}

			if ( $aPost['stream_id'] != '0' )
			{
				foreach(App::getParam('Mod_Video.stream_sources') as $aStream)
				{
					if ( $aStream['id'] == $aPost['stream_id'] )
					{
						if ( !eregi($aStream['url'], $aPost['vid_url']) )
						{
							$this->addErrors(App::format('Mod_Video.invalid.url', stripslashes($aStream['url'])));
						}
						break;
					}
				}
			}
			
			if (substr(trim($aPost['vid_url']), 0, 7) != 'http://') 
			{
				$this->addErrors(App::format('Mod_Video.invalid.url', stripslashes($aStream['url'])));	
			}

			if (!count($this->getErrors()))
            {
            	
            	if ($aPost['stream_id'] == 2)
            	{
            		if (($sGoogle = @file_get_contents($aPost['vid_url'])) && preg_match("/youtube.com\/watch\?v=(.*)/i", $sGoogle, $aMatch) && isset($aMatch[1]))
					{			
						$aPart = explode('">', $aMatch[1]);
						$aPost['vid_url'] = 'http://www.youtube.com/watch?v=' . $aPart[0];
						$aPost['stream_id'] = '1';
					}
            	}
            	
            	if ( App::getParam('vid_approve') )
            	{
					$iUploadedId = $oSrvVideo->addPendingVideo($aPost);
            	}
            	else
            	{
            		$iUploadedId = $oSrvVideo->addVideo($aPost);
            	}

				if ( App::getParam('vid_import') )
				{
					$sFileDestPath = (App::getParam('vid_approve') ? "pending_" : '');
					$aPost['vid_id'] = $iUploadedId;
					$oSrvVideo->importVideo($aPost, $sFileDestPath);
				}

				$sDestPath = App::getParam('video.image.path') . (App::getParam('vid_approve') ? "pending_" : '');

				if ( !count($this->getErrors()) && !empty($_FILES['image']['name']) )
				{
                	if ($oImage->upload('image', $sDestPath, $iUploadedId, 'jpg'))
                	{
                	    $oImage->loadInfo($sDestPath.$iUploadedId.'.jpg');
                	    $oImage->_checkLimits();
                	}

 					$this->addErrors($oImage->getErrors());

	                if (!count($this->getErrors()))
	                {
	                	$oImage->makeThumbnail($sDestPath.$iUploadedId.'.jpg', App::getSetting('upload_set_size_thumb'), App::getSetting('upload_set_size_thumb'));
	                }
				}
            }

			if ( isset($iUploadedId) && !count($this->getErrors()) )
			{
				if ( !file_exists($sDestPath.$iUploadedId.'.jpg') )
				{
					$bNoImageUploaded = true;
				}

				App::updateUserSpace();

				if ( !isset($bNoImageUploaded)   )
				{
					App::gotoUrl('public.account.submit.add-video', array('mode' => $oReq->get('mode'), 'uploaded' => $iUploadedId));
				}
			}
		}

		if ( $oReq->get('imageid') )
		{
			$bNoImageUploaded = true;
		}

        $this->oTpl->assignSrc('sValMess', $oValidator->makeJsMess());
        $this->oTpl->assignSrc('sValJs', $oValidator->makeJS());
		$this->oTpl->assign(array
		(
			'bApprovalSetting' => App::getParam('vid_approve'),
        	'aErrors' => $this->getErrors(),
			'aItems' => $oSrvVideo->getCategories(),
			'aStreamOptions' => App::getParam('Mod_Video.stream_sources'),
			'iUploadedId' => (isset($iUploadedId) ? $iUploadedId : $oReq->get('uploaded')),
			'iUsedSpace'     => $iUsedSpace,
            'iAllowedSpace'  => $iAllowedSpace,
            'iMaxUploadSize' => $iMaxUploadSize,
            'sMaxFileSize'   => floor($iMaxUploadSize / 1024),
            'bFfmpeg' => App::getParam('vid_import'),
            'bNoImageUploaded' => (isset($bNoImageUploaded) ? true : false),
            'aVal' => (isset($aPost) ? $aPost : ''),
		));

		return $this->oTpl->fetch('UploadStream.html');
    }
}
?>